package com.zzxx.utils;

import javax.imageio.ImageIO;
import com.google.zxing.*;
import java.awt.image.BufferedImage;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;

import com.google.zxing.common.BitMatrix;

import java.io.File;
import java.io.IOException;
import java.net.NetworkInterface;
import java.util.HashMap;
import com.google.zxing.common.HybridBinarizer;
import com.zzxx.exceptions.QrException;

import java.util.Map;

/**
 * @author li
 * @date 2021/06/03 15:38
 *
 * 生成二维码，保存图片到指定服务
 */
public class QrCodeCreateUtils {

	//生成二维码颜色
	private static final int BLACK = 0xFF000000;
	//生成二维码颜色
	private static final int WHITE = 0xFFFFFFFF;

	/**
	 * @Description:  示例代码
	 */
 	/*
 	public static void main(String[] args) throws Exception {
        CodeCreate("https://www.csdn.net/", 500, 500, "D:/code.jpg", "jpg");
    }*/

	/**
	 * 生成二维码
	 * @param text    二维码内容
	 * @param width    二维码宽
	 * @param height    二维码高
	 * @param outPutPath    二维码生成保存路径
	 * @param imageType     二维码生成格式
	 */
	public static void CodeCreate(String text, int width, int height, String outPutPath, String imageType){
		Map<EncodeHintType, String> his = new HashMap<EncodeHintType, String>();
		//设置编码字符集
		his.put(EncodeHintType.CHARACTER_SET, "utf-8");
		try {
			//生成二维码
			BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, his);
			//获取到二维码宽高
			int codeWidth = encode.getWidth();
			int codeHeight = encode.getHeight();
			//将二维码放入缓冲流中
			BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
			for (int i = 0; i < codeWidth; i++) {
				for (int j = 0; j < codeHeight; j++) {
					//循环将二维码内容套入图片
					image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
				}
			}
			File outPutImage = new File(outPutPath);
			//如果图片不存在创建图片
			if(!outPutImage.exists()) {
				outPutImage.createNewFile();
			}
			//将二维码写入图片
			ImageIO.write(image, imageType, outPutImage);
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 对二维码解析
	 * @param analyzePath    二维码路径
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String zxingCodeAnalyze(String analyzePath) throws IOException, QrException {
		String message = null;
//		try {
//			message = deEncodeByPath(analyzePath);
//		} catch (NotFoundException e) {
			QRImageUtils.binarization(analyzePath,analyzePath);
			QRImageUtils.opening(analyzePath,analyzePath);
			try {
				message = deEncodeByPath(analyzePath);
			} catch (NotFoundException notFoundException) {
				throw new QrException("noQr");
			}
//		}
		return message;
	}




	public static String zxingCodeAnalyze(File file) throws IOException, QrException {

		String s = zxingCodeAnalyze(file.getAbsolutePath());
		return s;

	}

	private static String deEncodeByPath(String path) throws NotFoundException {
		String content = null;
		BufferedImage image;
		try {
			File file = new File(path);
			image = ImageIO.read(file);
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			Binarizer binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
			Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
			content = result.getText();
		} catch (IOException e) {
			return null;
		}
//		catch (NotFoundException e) {
//			//这里判断如果识别不了带LOGO的图片，重新添加上一个属性
//			try {
//				image = ImageIO.read(new File(path));
//				LuminanceSource source = new BufferedImageLuminanceSource(image);
//				Binarizer binarizer = new HybridBinarizer(source);
//				BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
//				Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
//				//设置编码格式
//				hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
//				//设置优化精度
//				hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//				//设置复杂模式开启（我使用这种方式就可以识别微信的二维码了）
//				hints.put(DecodeHintType.PURE_BARCODE,Boolean.TYPE);
//				Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
//				content = result.getText();
//			} catch (IOException e1) {
//				return null;
//			}
//		}
		return content;
	}

	public static void main(String[] args) throws Exception {
		String hostAddress;

		try{
			hostAddress = NetworkInterface.getByName("wlan2").getInetAddresses().nextElement().getHostAddress();
		}catch (Exception e){
			hostAddress = NetworkInterface.getByName("wlan1").getInetAddresses().nextElement().getHostAddress();
		}

		QrCodeCreateUtils.CodeCreate("http://"+hostAddress+":8080/managerclient/login.html",
		180,180,"C:\\Users\\13465\\Desktop\\qr.jpg","jpg");
	}

}
